package com.supersoul.myself.controller;

import com.alibaba.fastjson.JSONObject;
import com.supersoul.myself.util.R;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotNull;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

@RestController
@RequestMapping("/data")
public class DataController {

    String TANG_SHI_DA_QUAN = "http://api.tianapi.com/txapi/poetries/index";

    String YI_ZHAN_DAO_DI = "http://api.tianapi.com/txapi/wenda/index";

    @GetMapping("/poetries")
    public R getPoetries(@RequestParam @NotNull Integer page) {
        String httpArg = "key=187af3c5c50f60abd64a6348e22535bc&num=1&page=" + page;
        String jsonRequest = DataController.request(TANG_SHI_DA_QUAN, httpArg);
        return R.success(jsonRequest);
    }

    @GetMapping("/yzdd")
    public R getYzdd() {
        String httpArg = "key=187af3c5c50f60abd64a6348e22535bc";
        String jsonRequest = DataController.request(YI_ZHAN_DAO_DI, httpArg);
        return R.success(jsonRequest);
    }


    public static String request(String httpUrl, String httpArg) {
        BufferedReader reader = null;
        String result = null;
        StringBuffer sbf = new StringBuffer();
        httpUrl = httpUrl + "?" + httpArg;

        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setRequestMethod("GET");
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }
            reader.close();
            result = sbf.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
